package com.luckku.boot.utils;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.FatalBeanException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;

/**
 * @author someone
 * @date notToday
 */


public class IsNull {
    /**
     * 整个类都校验
     */
    public static Boolean validateProperty(Object validateObj) {
        return validateProperty(validateObj,(String[])null);
    }
    /**
     * 类中的某些字段不校验
     */
    public static Boolean validateProperty(Object validateObj,String... ignoreProperties) {
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(validateObj.getClass());
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
        boolean flag = false;
        for (PropertyDescriptor targetPd : targetPds) {
            Method readMethod = targetPd.getReadMethod();
            if (readMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                try {
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(validateObj);
                    if (value instanceof String) {
                        if (StringUtils.isEmpty((String) value)) {
                            flag=true;
                            break;
                        }
                    }
                    if (value instanceof Float || value instanceof Integer) {
                        if (StringUtils.isEmpty(value.toString())) {
                            flag=true;
                            break;
                        }
                    }
                    if (value == null) {
                        flag=true;
                        break;
                    }
                } catch (Exception ex) {
                    throw new FatalBeanException(
                            "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                }
            }
        }
        return flag;
    }

}
